package com.lagou.miaosha.rocketmq.mq;

import com.alibaba.fastjson.JSONObject;
import com.lagou.miaosha.rocketmq.mapper.OrderMapper;
import com.lagou.miaosha.rocketmq.pojo.Order;
import com.lagou.miaosha.rocketmq.pojo.Stock;
import com.lagou.miaosha.rocketmq.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.concurrent.locks.Lock;

/**
 * @Description TODO
 * @Classname MyConsumeMsgListenerProcessor
 * @Date 2021/8/1 16:25
 * @Author ch'ien
 */

@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "ms_delay", topic = "${TOPIC.MS_DELAY}")
public class MyConsumeDelayMsgListenerProcessor implements RocketMQListener<Order> {

    @Autowired
    private IStockService stockService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(Order order){
        log.info("消息时 order：{}",order);
        if (order == null){
            return;
        }
        Order oneByOrderNo = orderMapper.getOneByOrderNo(order.getOrderNo());
        if (oneByOrderNo == null){
            return;
        }

        //未支付
        if (Objects.equals(oneByOrderNo.getStatus(), 0)){
//            库存恢复
            stockService.increment(oneByOrderNo.getGid());
            stockService.incrementStock(oneByOrderNo.getGid());

            //订单超时
            oneByOrderNo.setStatus(2);
            orderMapper.update(oneByOrderNo);
        }   else {
            return;
        }



    }

}
